package com.ruoyi.app.strategy.factory;

import com.ruoyi.app.domain.params.UserRegisterParam;
import com.ruoyi.app.domain.enums.RegisterTypeEnums;
import com.ruoyi.app.strategy.RegisterStrategy;
import com.ruoyi.app.strategy.impl.EmailRegisterStrategyImpl;
import com.ruoyi.app.strategy.impl.PhoneRegisterStrategyImpl;
import com.ruoyi.app.strategy.impl.WeChatRegisterStrategyImpl;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
public class RegisterFactory {

    /**
     * 存放所有注册策略
     */
    private final Map<Long, RegisterStrategy> registerStrategyMap = new HashMap<>();

    /**
     * 注入所有注册策略
     */
    @Autowired
    public RegisterFactory(WeChatRegisterStrategyImpl wechatRegisterStrategy,
                           EmailRegisterStrategyImpl emailRegisterStrategy,
                           PhoneRegisterStrategyImpl phoneRegisterStrategy) {
        this.registerStrategyMap.put(RegisterTypeEnums.WECHAT.getCode(), wechatRegisterStrategy);
        this.registerStrategyMap.put(RegisterTypeEnums.EMAIL.getCode(), emailRegisterStrategy);
        this.registerStrategyMap.put(RegisterTypeEnums.PHONE.getCode(), phoneRegisterStrategy);
    }

    public void register(UserRegisterParam userRegisterParam) throws ServiceException{
        RegisterStrategy strategy = registerStrategyMap.get(userRegisterParam.getRegisterType());
        Optional.ofNullable(strategy).orElseThrow(() -> new ServiceException("注册方式错误"));
        strategy.register(userRegisterParam);
    }
}
